package com.ibl.rover.lite.handler;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.bcel.generic.FLOAD;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hsqldb.lib.Sort;
import org.joda.time.DateTime;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.ibl.rover.lite.service.utill.Core.APPSETUP;
import com.ibl.rover.lite.service.utill.HibernateUtill;
import com.ibl.rover.lite.service.utill.Core.SST_TAGS;
import com.rover.lite.hibernate.dal.RvrAppsetup;
import com.rover.lite.hibernate.dal.RvrOrderDetails;
import com.rover.lite.hibernate.dal.RvrOrderDetailsId;
import com.rover.lite.hibernate.dal.RvrOrderHeads;
import com.rover.lite.hibernate.dal.RvrOrderHeadsId;
import com.sun.msv.datatype.xsd.IntegerValueType;
import com.ibl.rover.lite.service.utill.Core;
public class OrderHandler {

	
	Session session;
	Document doc;
	public OrderHandler(Document _doc) {
		// TODO Auto-generated constructor stub
			session = HibernateUtill.getSessionFactory().openSession();
		 doc=_doc;
		 
	}
	
	public String getAttributeValueByname(String name,Element orderItem){
		
	  	org.w3c.dom.NodeList attributesList = orderItem.getChildNodes();
	  	
	  	for (int index = 0 ; index<attributesList.getLength();index++){
		
	  		 if(name.equals( ((Element)attributesList.item(index)).getAttribute("name")))
	  		         return  ((Element)attributesList.item(index)).getAttribute("value");
	  		 
	  		 
	  	}
		return "";
	}
	
	
	
	@SuppressWarnings("unchecked")
	public boolean insertOrders(Element entityElement, Element bodyElement,String userName) throws ParseException   {
		
		try { 
	 
		RvrOrderHeads orderBean = null;
           String  docUser = ""; int dtpCode = 0, invdtpCode = 0;
           int status;
           int j = 2;
           int maxOrderID=0;
         
       	org.w3c.dom.NodeList orderEntityList = entityElement.getChildNodes();
           
//    	Transaction transaction = session.beginTransaction();
    	System.out.println("[insertOrders]   Username : "+userName
    			+"  Orders list:"+orderEntityList.getLength()+"  Start");
    	
           for (int index = 0; index <orderEntityList.getLength() ; index++) {
        	   Element orderItem =(Element)orderEntityList.item(index);
           	Transaction transaction = session.beginTransaction();
        	  
        System.out.println("[USer:"+userName+"] Order No."+Integer.parseInt( getAttributeValueByname("ORDER_ID",orderItem))+" Start");
                
        	   
        	   orderBean=new RvrOrderHeads();
        	   RvrOrderHeadsId ids=new RvrOrderHeadsId();
        	   
        	   if (getAttributeValueByname("SalesType",orderItem).equals("Cash")) {
                    docUser = "IO" + userName.substring(2);
                   dtpCode = 9;
                   invdtpCode = 2;
               } else if(getAttributeValueByname("SalesType",orderItem).equals("Credit")){
                   docUser = "CM" + userName.substring(2);
                   dtpCode = 4;
                   invdtpCode = 3;
               }else{
            	   docUser = "CQ" + userName.substring(2);
                   dtpCode = 6;
                   invdtpCode = 4;
               }
        	   
        	   
               if (getAttributeValueByname("STATUS",orderItem).equals("Active")) {
                   status = 0;
               } else {
                   status = 1;
               }
                 
              

               String toDate = Core.CONSTANT.toDateTimeFormat; //(String) dateFormatMap.get("toDateTimeFormat");
               String fromDate =  Core.CONSTANT.fromDateTimeFormat;//(String) dateFormatMap.get("fromDateTimeFormat");
               
               SimpleDateFormat format = new SimpleDateFormat(toDate);
               
               Date date = new Date();
               format.format(date);
               String dateString = DateFormatUtils.format(date, fromDate);
               Date afterDate = DateUtils.addDays(date, 1);
               String afterDateString = DateFormatUtils.format(afterDate, fromDate);

//               DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//               Date oldDate = (Date)formatter .parse((new Date()).toString());
//               
               
//               Calendar cal = Calendar.getInstance(); 
//               cal.setTime(new SimpleDateFormat("dd-MMM-yyyy").parse((new Date()).toString())); 
//               
             //Setting Order_head
               
               
               
               ids.setDocno(
//            		   Integer.parseInt( orderItem.getAttribute("ORDER_ID").toString())
            		   Integer.parseInt( getAttributeValueByname("ORDER_ID",orderItem))
            		   );
               if(ids.getDocno() > maxOrderID)
            	   maxOrderID=ids.getDocno();
               
               ids.setDocSer(docUser);
               ids.setDtpDoccode(dtpCode);
               ids.setPayCode(1);
               ids.setExtdocamt(Double.parseDouble( 
//            		   orderItem.getAttribute("Amount").toString())
            		    getAttributeValueByname("Amount",orderItem)
            		   ));
               ids.setDocnetamt(
//            		   Double.parseDouble( orderItem.getAttribute("Amount").toString())
            		   ids.getExtdocamt()
            		   );
               ids.setTotaldocamt(
//            		   Double.parseDouble( orderItem.getAttribute("Amount").toString())
            		   ids.getExtdocamt()
            		   
            		   );
               ids.setDocdate(DateUtils.parseDate(dateString, new String[]{fromDate}));
               ids.setDuedate(DateUtils.parseDate(afterDateString, new String[]{fromDate}));
               ids.setReqdate(DateUtils.parseDate(afterDateString, new String[]{fromDate}));
               ids.setInvdate(DateUtils.parseDate(afterDateString, new String[]{fromDate}));
               ids.setCopies(0);
               ids.setCanceled(0);
               ids.setOrderStatus(status);
               ids.setCusCode(
//			orderItem.getAttribute("CustomerCode").toString()
            		   getAttributeValueByname("CustomerCode",orderItem)
);
               ids.setVsrCode(userName);
               ids.setVisCode(2);
               ids.setHoldOrderTag(1);
               ids.setAppType(0);
               // Setting Quantity
               ids.setSumqnt(getQnty(
//            		   orderItem.getAttribute("PRODUCT_ORDER_BEAN_QUANTITY").toString())
            		   getAttributeValueByname("PRODUCT_ORDER_BEAN_QUANTITY",orderItem))
            		   );
               ids.setSumqntcases(0.0);
               ids.setPaydiscrate(0.0);
               ids.setDistdisccode(127);
               ids.setDistdiscrate(0.0);
               ids.setDocdisccode(127);
               ids.setDocdiscrate(0.0);
               ids.setCustdisccode(127);
               ids.setCustdiscrate(0.0);
               ids.setVoldisccode(127);
               ids.setVoldiscrate(0.0);
               ids.setDiscvsrflag(0);
               ids.setTaxOnTotal(0);
               ids.setInvDtpCode(invdtpCode);
               ids.setEditid("Rover");
               ids.setDisc2vsrflag(0);
               
               orderBean.setId(ids);
               
               //Setting Order Details
               
              String[] orderDeatilCodes =   //orderItem.getAttribute("PRODUCT_ORDER_BEAN_CODE").toString()

            		  getAttributeValueByname("PRODUCT_ORDER_BEAN_CODE",orderItem)
            		  .split(",");
              String[] orderUnitPrices = 
//            		  orderItem.getAttribute("UNITPRICE").toString()
            		  getAttributeValueByname("UNITPRICE",orderItem)
            		  .split(",");
              String[] orderDetailQNTY=
//            		  orderItem.getAttribute("PRODUCT_ORDER_BEAN_QUANTITY").toString()
            		  getAttributeValueByname("PRODUCT_ORDER_BEAN_QUANTITY",orderItem)
            		  .split(",");
              
              
              session.save(orderBean);
              
              
        	  
              List<RvrOrderDetails> detailsArray=new ArrayList<RvrOrderDetails>();
              System.out.println("Product order Size :"+orderDeatilCodes.length);
              //Iterate over Number of detail
              for (int i = 0; i < orderDeatilCodes.length; i++) {
            	  
            	  RvrOrderDetails orderDetail=new RvrOrderDetails();
            	  RvrOrderDetailsId orderDetailids=new RvrOrderDetailsId();
            	  
            	  orderDetailids.setDhdDocno(ids.getDocno());
            	  orderDetailids.setDhdDocser(ids.getDocSer());
            	  orderDetailids.setDhdDtpDoccode(ids.getDtpDoccode());
            	  orderDetailids.setProCode(orderDeatilCodes[i]);
            	  orderDetailids.setUom(1);
            	  orderDetailids.setProdprice(Double.parseDouble(orderUnitPrices[i]));
            	  orderDetailids.setOrigprodprice(Double.parseDouble(orderUnitPrices[i]));
            	  orderDetailids.setPiecesOrdered(Integer.parseInt(orderDetailQNTY[i]));
            	  orderDetailids.setPiecesShipped(Integer.parseInt(orderDetailQNTY[i]));
            	  orderDetailids.setExtlinamt(Double.parseDouble(orderUnitPrices[i]));
            	  orderDetailids.setProdnetval(Double.parseDouble(orderUnitPrices[i]));
            	  orderDetailids.setTotline(Double.parseDouble(orderUnitPrices[i]));
            	  orderDetailids.setDiscval(0.0);
            	  orderDetailids.setDiscrate(0.0);
            	  orderDetailids.setSkudisccode(127);
            	  orderDetailids.setSkudiscval(0.0);
            	  orderDetailids.setSkudiscrate(Float.parseFloat("0") );
            	  orderDetailids.setLineTaxKey("null");
            	  orderDetailids.setLineSequence(0);
            	  orderDetailids.setEditid("Rover");
            	  orderDetailids.setDisc3skuflag(0);
            	  orderDetailids.setBasepriceflag(0);
            	  orderDetailids.setTsoCode(userName);

            	  orderDetail.setId(orderDetailids);
            	  session.save(orderDetail);  
//            	  detailsArray.add(orderDetail);
            	 
			}
          System.out.println("[USer:"+userName+"] Order No."+Integer.parseInt( getAttributeValueByname("ORDER_ID",orderItem))+" End");

        	  
          transaction.commit();
                    
               
           }       
           
     
         	
           	
           setlastOrderNoInAppSetup(userName,maxOrderID);
//           
//           session.getTransaction().commit();
//           transaction.commit();
//       	
   		List<RvrOrderHeads> customer_list = new ArrayList<RvrOrderHeads>();


   		Criteria criteria = session.createCriteria(RvrOrderHeads.class);

   		
   		customer_list = criteria.list();
   		customer_list.size();
   		System.out.println("[insertOrders]   Username : "+userName
    			+"  Orders list:"+orderEntityList.getLength()+"  End");
       	
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//throw e;
				return false;
			}     
			   
		return true;
				
           
          
//		Criteria rvrAppsetupCriteria = session.createCriteria(RvrAppsetup.class);
//		rvrAppsetupCriteria.add(Restrictions.eq("id.tsoCode", userName));
//		List<RvrAppsetup>  listAppSetup = new ArrayList<RvrAppsetup>();
//		listAppSetup=rvrAppsetupCriteria.list();
//
//		Element entityElement = doc.createElement("entity");
//		entityElement.setAttribute("name", SST_TAGS.APPSETUP);
//		bodyElement.appendChild(entityElement);
//
//		Element addElement = doc.createElement("add");
//		entityElement.appendChild(addElement);
//		
//		
//		for (RvrAppsetup rvrAppsetup : listAppSetup) {
//			Element itemElement = doc.createElement("item");
//			addElement.appendChild(itemElement);
//			setRvrAppsetupAttribute(rvrAppsetup, itemElement);
//
//		}

		
	}

	
	
	public void setlastOrderNoInAppSetup(String userName,Integer maxOrderId){

//		Criteria rvrOrderHeadsCriteria = session.createCriteria(RvrOrderHeads.class);
//		rvrOrderHeadsCriteria.add(Restrictions.eq("id.vsrCode", userName.trim()));
//		rvrOrderHeadsCriteria.addOrder(Order.desc("id.docno"));
//				
//		List<RvrOrderHeads>  listOrderHeads = new ArrayList<RvrOrderHeads>();
//		
//		listOrderHeads=rvrOrderHeadsCriteria.list();
//		if(listOrderHeads.size() > 0){
//		
//				 

//				Criteria rvrAppsetupCriteria = session.createCriteria(RvrAppsetup.class);
//				rvrAppsetupCriteria.add(Restrictions.eq("id.tsoCode", userName));
//				List<RvrAppsetup>  listAppSetup = new ArrayList<RvrAppsetup>();
//				listAppSetup=rvrAppsetupCriteria.list();
//				
//				for (RvrAppsetup rvrAppsetup : listAppSetup) {
////					Element itemElement = doc.createElement("item");
////					addElement.appendChild(itemElement);
////					setRvrAppsetupAttribute(rvrAppsetup, itemElement);
////					rvrAppsetup app=session.get(RvrAppsetup.class,new Long(1));
//					
//					rvrAppsetup.getId().setLastOrderNo(maxOrderId.toString());
////					session.update(rvrAppsetup);
//					
					
				String query="UPDATE RvrAppsetup set LAST_ORDER_NO = :newName WHERE TSO_CODE = :name";
//				session.createQuery( query).setParameter(0, userName);
//				
//				  String hql = "update Supplier set name = :newName where name = :name";
			        Query querya = session.createQuery(query);
			        querya.setString("name",userName);
			        querya.setString("newName",maxOrderId.toString());
			        int rowCount = querya.executeUpdate();
				
//				}

	 
		
		
		

	}
	
	public int getQnty(String Qnty){
		
		String[] qntyArray=Qnty.split(",");
		int Sum	= 0;
        for (int i = 0; i < qntyArray.length; i++) {
        	
        	Sum+=Integer.parseInt(qntyArray[i]);
        }
		
		return Sum;
	}
	
}
